/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package syslivros;

import java.awt.event.KeyEvent;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class Consulta_Cursos extends javax.swing.JFrame {

    public static String tabela;
    public static ArrayList<StringBuilder> linhas;

    /**
     * Creates new form Consultar
     */
    public Consulta_Cursos() {
        initComponents();
        try {
            Conexao.conectar("root", "positivo");
            System.out.println("conetado!ура товарищи!");

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro ao conectar ao banco" + ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }

        try {
            PopulaComboCatis();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar catis" + ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }
        //try{PopulaComboCurso();}catch(Exception ex1){
        //JOptionPane.showMessageDialog(this,"Erro ao carregar curso "+ ex1.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
        //}

    }

    public void PopulaComboCatis() throws SQLException {
        String SQL = "select NomeCatis  from Catis  ";
        ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
        DefaultComboBoxModel model = (DefaultComboBoxModel) cbLocal.getModel();
        model.removeAllElements();
        while (rs.next()) {
            model.addElement(rs.getString("NomeCatis"));
        }

    }
    /*public void PopulaComboCurso()throws  SQLException{
     String SQL="select NomeCurso  from listacursos  ";
     ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
     DefaultComboBoxModel model =(DefaultComboBoxModel) cbApostila.getModel();
     model.removeAllElements();
     while(rs.next()){
     model.addElement(rs.getString("NomeCurso"));
     }

     }*/

    public void consultar() throws FileNotFoundException {
        DefaultTableModel model = (DefaultTableModel) table_consulta.getModel();
        model.setRowCount(0);
        //String Apostila = (String) cbApostila.getSelectedItem();
        String Local = (String) cbLocal.getSelectedItem();
        String SQL = "SELECT IdEstoqueCurso, nm_curso, (case nm_periodo when 'm' then 'Manhã' when 't' then 'Tarde' when 'n' then 'Noite' end ) nm_periodo,"
                + " qt_apostila, nm_local, dt_data_entrega FROM estoque_curso"
                + " WHERE lower(nm_Local)"
                + " LIKE '%" + Local.toLowerCase() + "%'";

        // String SQL = "select * from estoque_curso";
        try {
            Statement stmt = Conexao.ConexaoJDBC.createStatement();

            try {
                try (ResultSet rs = stmt.executeQuery(SQL)) {
                    while (rs.next()) {

                        model.addRow(new Object[]{
                                    rs.getInt("IdEstoqueCurso"), rs.getString("nm_Curso"), rs.getString("nm_periodo"), rs.getInt("qt_apostila"), rs.getString("nm_local"), rs.getString("dt_data_Entrega")});
                        
                    }
                    linhas = new ArrayList<>();
                    StringBuilder b;
                    for (int i = 0; i < table_consulta.getRowCount(); i++) {
                        b = new StringBuilder();
                        for (int j = 0; j < table_consulta.getColumnCount(); j++) {
                            if(j%6==0){
                            b.append(table_consulta.getValueAt(i, j)).append("; \n");
                                    
                            }else{b.append(table_consulta.getValueAt(i, j)).append(" ");
                            }
                        } linhas.add(b);
                       
                    }



                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro 1" + ex.getMessage());
            }
        } catch (Exception ex2) {
            JOptionPane.showMessageDialog(this, "Erro 2" + ex2.getMessage());


        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnVoltar = new javax.swing.JButton();
        btnGerarRelatorio = new javax.swing.JButton();
        lblLocal = new javax.swing.JLabel();
        cbLocal = new javax.swing.JComboBox();
        btnConsultar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        table_consulta = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Consultar");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });
        btnVoltar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnVoltarKeyPressed(evt);
            }
        });

        btnGerarRelatorio.setText("Gerar Relatório");
        btnGerarRelatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarRelatorioActionPerformed(evt);
            }
        });
        btnGerarRelatorio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnGerarRelatorioKeyPressed(evt);
            }
        });

        lblLocal.setText("Local: ");

        cbLocal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione um Catis", "Base", "Centro Tecnológico (Sala 72)", "Centro Tecnológico (Sala 73)", "CECAP", "PROA", "Lúcio Martins", "Espaço da Juventude", "Sub Prefeitura (Lab. 1)", "Sub Prefeitura (Lab. 2)", "Saulo de Tarso", " " }));

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });
        btnConsultar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnConsultarKeyPressed(evt);
            }
        });

        table_consulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "CURSO", "PERIODO", "QUANTIDADE", "LOCAL", "DATA DE ENTREGA"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table_consulta);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblLocal)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbLocal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 880, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnConsultar)
                        .addGap(303, 303, 303)
                        .addComponent(btnGerarRelatorio)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnVoltar)
                        .addGap(28, 28, 28))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLocal)
                    .addComponent(cbLocal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 82, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGerarRelatorio)
                    .addComponent(btnVoltar)
                    .addComponent(btnConsultar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-916)/2, (screenSize.height-432)/2, 916, 432);
    }// </editor-fold>//GEN-END:initComponents

    private void btnVoltarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnVoltarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnVoltarActionPerformed(null);
        }
    }//GEN-LAST:event_btnVoltarKeyPressed

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        new Consultar().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        /* if (!cbApostila.getSelectedItem().equals("Selecione uma Apostila")    && (!cbLocal.getSelectedItem().equals("Selecione um Catis"))) {
         lblApostila.setForeground(Color.black);
         lblLocal.setForeground(Color.black);
         consultar();//chamada do metodo consultar
         } else {
         if (cbApostila.getSelectedItem().equals("Selecione uma Apostila")) {
         JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Apostila\"", "Erro", JOptionPane.ERROR_MESSAGE);
         lblApostila.setForeground(Color.red);
         } else {

         lblApostila.setForeground(Color.black);
         }
         if (cbLocal.getSelectedItem().equals("Selecione um Catis")) {
         JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Catis\"", "Erro", JOptionPane.ERROR_MESSAGE);
         lblLocal.setForeground(Color.red);
         } else {}*/
        // lblLocal.setForeground(Color.black);
        try {
            consultar();
        } catch (Exception ex2) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar curso " + ex2.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }
        //}}



    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnConsultarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnConsultarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnConsultarActionPerformed(null);
        }
    }//GEN-LAST:event_btnConsultarKeyPressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {
            Conexao.desconectar();
            System.out.println("Desconectado!");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao desconectar o banco" + ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_formWindowClosed

    private void btnGerarRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarRelatorioActionPerformed
        try { 
            SysLivros.geraRelatorio_ApostilasEnviadasDOC(linhas);
        } catch (FileNotFoundException ex) {
            System.out.println("ERRO");
        }




    }//GEN-LAST:event_btnGerarRelatorioActionPerformed

    private void btnGerarRelatorioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnGerarRelatorioKeyPressed
        btnGerarRelatorioActionPerformed(null);
    }//GEN-LAST:event_btnGerarRelatorioKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Consulta_Cursos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Consulta_Cursos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Consulta_Cursos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Consulta_Cursos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Consulta_Cursos().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnGerarRelatorio;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbLocal;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblLocal;
    private javax.swing.JTable table_consulta;
    // End of variables declaration//GEN-END:variables
}
